package org.example.controller;

import jakarta.annotation.Resource;
import org.example.pojo.Video;
import org.example.service.VideoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 视频文件管理控制器
 *
 * @author rjs
 */

@RestController
@RequestMapping("/video")
public class VideoController {
    private static final Logger logger = LoggerFactory.getLogger(VideoController.class);
    @Resource
    private VideoService videoService;

    /**
     * 上传视频
     *
     * @param file 视频文件
     * @return 是否上传成功
     */
    @PostMapping("/upload")
    public boolean uploadVideo(@RequestParam("file") MultipartFile file) {
        try {
            Video video = new Video();
            video.setVideo(file.getBytes());
            return videoService.save(video);
        } catch (IOException e) {
            logger.error("上传视频时出错", e);
            return false;
        }
    }

    /**
     * 获取视频详情
     *
     * @param id 视频id
     * @return 视频数据和元信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<byte[]> getVideoById(@PathVariable Long id) {
        Optional<Video> videoOptional = Optional.ofNullable(videoService.getById(id));
        if (videoOptional.isPresent()) {
            Video video = videoOptional.get();
            byte[] videoData = video.getVideo(); // Assuming getVideo() returns byte[]
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("video/mp4"));
            return new ResponseEntity<>(videoData, headers, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 更新视频
     *
     * @param video 视频对象
     * @return 是否更新成功
     */
    @PutMapping
    public boolean updateById(@RequestBody Video video) {
        return videoService.updateById(video);
    }

    /**
     * 删除视频
     *
     * @param id 视频id
     * @return 是否删除成功
     */
    @DeleteMapping("/{id}")
    public boolean removeById(@PathVariable Long id) {
        return videoService.removeById(id);
    }

    /**
     * 获取所有视频
     *
     * @return 视频列表
     */
    @GetMapping
    public List<Long> listAll() {
        return videoService.list().stream().map(Video::getId).collect(Collectors.toList());
    }
}
